import http from '@/utils/request.ts'
import type { Navbar, CreateNavbarRequest, UpdateNavbarRequest, NavbarSortUpdateRequest } from '@/modules/navbar/types/navbar.ts'

// 转换导航项目ID为字符串
function convertNavbarIds(navbar: any): Navbar {
  return {
    ...navbar,
    id: String(navbar.id),
    children: navbar.children ? navbar.children.map(convertNavbarIds) : undefined
  }
}

export const navbarApi = {
  // 获取所有导航栏项目（平面列表）
  getAll: async (): Promise<Navbar[]> => {
    const response = await http.get<any[]>('/navbar/list')
    const data = response.data || []
    return data.map(convertNavbarIds)
  },
  
  // 获取树形结构的导航栏项目
  getTree: async (): Promise<Navbar[]> => {
    const response = await http.get<Navbar[]>('/navbar/tree')
    return response.data || []
  },

  // 根据ID获取导航栏项目
  getById: async (id: string): Promise<Navbar> => {
    const response = await http.get<Navbar>(`/navbar/${id}`)
    return response.data
  },

  // 创建导航栏项目
  create: async (request: CreateNavbarRequest): Promise<Navbar> => {
    const response = await http.post<Navbar>('/navbar', request)
    return response.data
  },

  // 更新导航栏项目
  update: async (id: string, request: UpdateNavbarRequest): Promise<Navbar> => {
    const response = await http.put<Navbar>(`/navbar/${id}`, request)
    return response.data
  },

  // 删除导航栏项目
  delete: async (id: string): Promise<boolean> => {
    const response = await http.delete<boolean>(`/navbar/${id}`)
    return response.data
  },

  // 批量更新导航栏排序
  updateSort: async (request: NavbarSortUpdateRequest): Promise<boolean> => {
    const response = await http.put<boolean>('/navbar/sort', request)
    return response.data
  }
}